// components/search/index.js
import {Keyword} from '../../models/keyword';
import { BookModel } from '../../models/book';
const bookModel=new BookModel();
const keyword=new Keyword();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
      topMore:{
        type:Number,
        observer:"onPull"
      },
      bottomMore:{
        type:Number,
        observer:"onBottom"
      }
  },

  /**
   * 组件的初始数据
   */
  data: {
  words:[],
  hots:[],
  books:[],
  isSearch:false,
  value:"",
  isResult:false,
  isClear:false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPull(){
      this.setData({
        books:[]
      })
      bookModel.getBookSearch(0,this.data.value).then(res=>{
        this.setData({
          books:res.books
        })
      })
    },
    onBottom(){
     const start=this.data.books.length;
     let value=this.data.value;
     bookModel.getBookSearch(start,value).then(res=>{
     this.data.books.push(...res.books);
      this.setData({
        books:this.data.books
      })
    })
    },
     onConfirm(event){
       wx.showLoading({
         title:'数据加载中',
       })
       let value=event.detail.value;
       bookModel.getBookSearch(0,value).then(res=>{
         if(res.total){
           keyword.addHistory(value);
           let words=keyword.getHistory();
           this.setData({
             words,
             books:res.books,
             isSearch:true,
             isResult:false,
             isClear:true,
             value,
             total:res.total
           })
           wx.hideLoading()
         }else{
           wx.showToast({
             title: '抱歉,你搜索的内容为空',
             icon: 'none'
           })
           this.setData({
             isSearch:true,
             isResult:true,
             isClear:true,
             value,
             books:[]
           })
         }
       })
     },
     onInput(event){
       const value=event.detail.value;
       if(value){
         this.setData({
           isClear:true
         })
       }else{
         this.setData({
           isClear:false
         })
       }
     },
     onClear(){
          this.setData({
            value:"",
            isSearch:false,
            isResult:false,
            isClear:false,
            books:[]
          })
     },
     onCancel(){
       wx.switchTab({
         url: '/pages/book/book',
       })
     }
  },
  attached(){
    // keyword.getHistory();
    this.setData({
      words:keyword.getHistory()
    })
    keyword.getHotData().then(res=>{
      this.setData({
        hots:res.hot
      })
    })
  }
})
